package com.bosssoft.g1.common.annotation;

import com.google.gson.Gson;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * 系统日志，切面处理类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Aspect
public class SysLogAspect {
    @Pointcut(value="execution(* com.bosssoft.g1.common.*.*.*(..))")
    public void point(){

    }

    /**
     * 前置通知
     * @param joinPoint
     */
    @Before(value="point()")
    public void before(ProceedingJoinPoint joinPoint) {
        System.out.println("transaction begin");

        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        System.out.println("Request Parameters: " + new Gson().toJson(args));
    }

    /**
     * 后置通知
     * @param result
     */
    @AfterReturning(pointcut = "point()", returning = "result")
    public void after(Object result) {
        System.out.println("transaction commit");

        // 记录返回值
        System.out.println("Response: " + new Gson().toJson(result));
    }

    @Around("point()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录前置信息
        System.out.println("transaction begin");

        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        System.out.println("Request Parameters: " + new Gson().toJson(args));

        // 执行方法
        Object result = joinPoint.proceed();

        // 记录后置信息
        System.out.println("transaction commit");

        // 记录返回值
        System.out.println("Response: " + new Gson().toJson(result));

        return result;
    }
}